import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
// import { HttpHeaders } from '@angular/common/http';
// import { HttpClient } from '@angular/common/http';

import { Holidays } from '../domain/holidays';

import { ApiService } from './api.service';
import { postHolidays } from '../domain/holidays'
import { postPatchHolidays } from '../domain/holidays'
import { $ } from 'protractor';
import { Observable } from 'rxjs';

const httpOptions = {
  headers : new Headers ({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})


export class HolidayService {
  private api_url ;
  private headers ;


  constructor(private http: Http, private apiService: ApiService) { 
    this.api_url = apiService.getUrl() + 'holidays/'
    this.headers = apiService.getHeaders();
  }

  getHolidays() : Promise<Holidays[]> {
    const url = `${this.api_url}` + "applicants/";
    let options = new RequestOptions({headers: this.headers, withCredentials: true})
    return this.http.get(url, options) 
      .toPromise()
      .then(res => res.json() as Holidays[])
      .catch(this.handleError);
  }

  getHolidaysByID(ID: string) : Promise<Holidays[]> {
    const url = `${this.api_url}`+"applicants/"+ID+"/";
    return this.http.get(url, {withCredentials: true}) 
      .toPromise()
      .then(res => res.json() as Holidays[])
      .catch(this.handleError);
  }

  createHolidays(holidayJSON: postHolidays) : Promise<postHolidays> {
    const url = `${this.api_url}`+ "applicants/";
    let options = new RequestOptions({headers: this.headers, withCredentials: true})
    console.log(JSON.stringify(holidayJSON));
    console.log(this.headers);
    return this.http
      .post(url, JSON.stringify(holidayJSON), options)
      .toPromise()
      .then(res => res.json() as string)
      .catch(this.handleError);
  }

  patchHolidays(postPatchHoliday: postPatchHolidays, ID: string) : Promise<Holidays> {
    const url = `${this.api_url}` + 'managers/' + ID + "/";
    return this.http
    .patch(url, JSON.stringify(postPatchHoliday))
    .toPromise()
    .then(res => res.json() as Holidays)
    .catch(this.handleError)
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    alert("发生了错误❌");
    return Promise.reject(error.message || error);
  }
}
